﻿using System.ComponentModel.Composition;
using System.Windows;
using Caliburn.Micro;
using CoProjectDF.Repository;
using CoProjectModel;
using Coproject.Framework;
using Coproject.ViewModels.Interfaces;
using IdeaBlade.Application.Framework.Core.Authentication;
using IdeaBlade.EntityModel;

namespace Coproject.ViewModels
{
    [ExportModule(50)]
    public class AdminViewModel : Screen, IModule
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly IUserRepository _repository;
        private BindableCollection<User> _users;

        [ImportingConstructor]
        public AdminViewModel(IUserRepository repository, IAuthenticationService authenticationService)
        {
            _repository = repository;
            _authenticationService = authenticationService;

            DisplayName = "Admin";
            Description = "Read Only view of Users";
        }

        [Import(RequiredCreationPolicy = CreationPolicy.Shared)]
        public IBusyWatcher Busy { get; set; }

        public BindableCollection<User> Users
        {
            get { return _users; }
            private set
            {
                _users = value;
                NotifyOfPropertyChange(() => Users);
            }
        }

        #region IModule Members

        public string Description { get; private set; }

        #endregion

        public AdminViewModel Start()
        {
            _repository.GetUsers((r) =>
                                     {
                                         //Success
                                         Users = new BindableCollection<User>(r);
                                     });
            return this;
        }

        public void GetUsers()
        {
            Busy.AddWatch();
            INotifyCompleted nc = _repository.GetUsers(
                (r) =>
                    {
                        //Success
                        Users = new BindableCollection<User>(r);
                        Busy.RemoveWatch();
                    },
                (e) =>
                    {
                        //Fail
                        Busy.RemoveWatch();
                        if (e != null)
                        {
                            MessageBox.Show(e.Message, "System Error", MessageBoxButton.OK);
                        }
                    });
        }

        protected override void OnActivate()
        {
            if (!_authenticationService.IsLoggedIn)
            {
                Description = "Login required to view Admin data.";
                if (Users != null)
                    Users.Clear();
                return;
            }
            Description = "Read Only view of Users";
            GetUsers();
            base.OnActivate();
        }
    }
}